package com.lgq.auth.service.security;

import com.lgq.auth.dao.UserMapper;
import com.lgq.auth.entity.User;
import com.lgq.common.constant.constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysUserDetailsService implements UserDetailsService {

	@Autowired
	private UserMapper userMapper;

	@Override
	public User loadUserByUsername(String username) throws UsernameNotFoundException {

		User user = userMapper.selectOneByObj(username);

		if (user == null) {
			throw new UsernameNotFoundException(username);
		}

		List<String> list = new ArrayList<>();
		list.add(constant.OAUTH_ROLE + "ADMIN");

		Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
		/*Iterator<String> iterator =  userMapper.selectPermission(user.getId()).iterator();
		while (iterator.hasNext()){
			collection.add(new SimpleGrantedAuthority(iterator.next()));
		}*/
		for(String permission : list) {
			collection.add(new SimpleGrantedAuthority(permission));
		}

		// return user;
		return new User(user.getId(), user.getUsername(), user.getPassword(), user.getNickname(), collection);
	}
}
